package framework.ui;

import java.util.ArrayList;
import java.util.List;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;

public class MovablePane extends Pane {
	
	protected double yoffset;
	protected double xoffset;
	protected boolean dragged;
	private List<MovablePaneHandler> handlers = new ArrayList<MovablePaneHandler>();
	
	public MovablePane(final Pane content, String title, final MovablePaneHandler handler) {
		VBox vbox = new VBox();
		handlers.add(handler);
		this.getChildren().add(vbox);
		final Button headerWidget = new Button(title);
		vbox.getChildren().add(headerWidget);
		vbox.getChildren().add(content);
		headerWidget.prefWidthProperty().bind(vbox.widthProperty());

		headerWidget.setOnMousePressed(new EventHandler<MouseEvent>() {
			@Override
			public void handle(MouseEvent arg0) {
				xoffset = arg0.getX();
				yoffset = arg0.getY();
				dragged = false;
			}
		});
		
		headerWidget.setOnMouseDragged(new EventHandler<MouseEvent>() {
			@Override
			public void handle(MouseEvent arg0) {
				updatePosition(arg0.getSceneX() - xoffset, arg0.getSceneY() - yoffset);
				dragged = true;
			}
		});
		
		headerWidget.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent arg0) {
				if (!dragged) {
					fireOnSelect();
				}
			}
		});
		headerWidget.setOnMouseClicked(new EventHandler<MouseEvent>() {
			@Override
			public void handle(MouseEvent arg0) {
				if (arg0.getClickCount() == 2) {
					content.setVisible(!content.isVisible());
				}
			}			
		});
		
		this.layoutXProperty().addListener(new ChangeListener<Number>() {
			@Override
			public void changed(ObservableValue<? extends Number> arg0,
					Number arg1, Number arg2) {
				//System.out.println(arg2.doubleValue());
				fireOnMove(arg2.doubleValue(), MovablePane.this.layoutYProperty().get());
			}
		});
	}
	
	protected void fireOnMove(double x, double y) {
		for (MovablePaneHandler handler : handlers) {
			handler.onMove(x, y);
		}
	}

	protected void fireOnSelect() {
		for (MovablePaneHandler handler : handlers) {
			handler.onSelect(this);
		}
	}

	protected void updatePosition(double sceneX, double sceneY) {
		this.setLayoutX(sceneX);
		this.setLayoutY(sceneY);
	}

	public void addMovablePaneHandler(MovablePaneHandler handler) {
		this.handlers.add(handler);
	}
}
